<?php
/**
 * 银行首页
 */
namespace app\api\modules\v1\bank\controllers;

use yii\web\Controller;
use app\api\components\ApiController;
use Yii;
use app\api\modules\v1\bank\models\BankApp;
use \yii\helpers\ArrayHelper;
use app\models\base\BankAccount;
use \yii\data\Pagination;
use app\backend\widgets\LinkPager;
use app\api\modules\v1\market\models\UrlHandler;
use app\models\base\User;
use app\models\base\Activity;
use app\models\base\Project;

class DefaultController extends ApiController
{
	public function init()
	{
		 parent::init(); // TODO: Change the autogenerated stub
	}

	/**
	 * [银行基本信息]
	 * @return [array] [description]
	 */
    public function actionIndex()
    {   	
        $bank = BankApp::getBank();

        return parent::sendMessageJson('获取数据成功',200,$bank);
    }

    /**
     * [个人银行账户]
     * @return [type] [description]
     */
    public function actionList()
    {
    	$page = Yii::$app->request->get('page',1);

    	$model = BankAccount::find()->where(['disabled'=>0]);

    	$pages = new Pagination([
    			'totalCount' => $model->count(),
                'defaultPageSize' => 20,
    		]);


    	//判断用户输入的page是否大于总页数
        if($page > ceil(($pages->totalCount)/($pages->limit))){
            return ['code'=>self::$CODE_SUC,'msg'=>'获取成功','page'=>'','data'=>['list'=>[]]];
        }

    	$model->limit($pages->limit);

    	$model->offset($pages->offset);

    	$model->orderBy('account_id');

    	$bankaccount = $model->all();

        if(!$bankaccount){
            return ['code'=>self::$CODE_SUC,'msg'=>'获取成功','data'=>['list'=>[]],'page'=>''];
        }

    	$list = BankApp::getOwnBank($bankaccount);

        //待入账和待审核数量
        $list = self::number($list);

    	$pagesize = LinkPager::widget([
                    'pagination' => $pages,
                    'firstPageLabel' => "首页",
                    'prevPageLabel' => '上一页',
                    'nextPageLabel' => '下一页',
                    'lastPageLabel' => '末页',
                ]);

    	return ['code'=>self::$CODE_SUC,'msg'=>'获取成功','data'=>['list'=>$list],'page'=>$pagesize];
    	// var_dump(ArrayHelper::toArray($bankaccount));
    }

    /**
     * [个人银行列表排序]
     * @return [type] [description]
     */
    public function actionOrderList()
    {

    	$get = Yii::$app->request->get();

    	$page = Yii::$app->request->get('page',1);
        if(empty($get['status']) || !isset($get['status'])){
            //选择全部   
        	$query = (new \yii\db\Query())->select(['account_id','name',new \yii\db\Expression('all_value/8 as all_value'),new \yii\db\Expression('all_gold/8 as all_gold'),new \yii\db\Expression('all_cost/8 as all_cost'),new \yii\db\Expression('FORMAT(all_value/all_cost,2) as vcost'),new \yii\db\Expression('FORMAT(all_gold/all_cost,2) as gcost'),new \yii\db\Expression('FORMAT(all_value/all_gold,2) as vgold'),'bk.user_id as user_id'])->from(BankAccount::tableName().' AS bk')->innerJoin(User::tableName().' AS user','user.user_id=bk.user_id');

        	$query = UrlHandler::handle_get($query,$get,['page','status']);

        	$query = $query->andWhere(['bk.disabled'=>0]);

        	$data = BankApp::pagination($query,20,$page);

            //待入账和待审核数量同时把价值等数据约等于一位小数
            $list = self::number($data['list']);
        }else{
            //选择具体的范围(需要查询活动表)
            $data = BankApp::rangeinfo($get,$page);
            // var_dump($data);exit;
            $list = self::number($data['list']); 
        }

    	return ['code'=>self::$CODE_SUC,'message'=>'获取数据成功','data'=>['list'=>$list],'page'=>$data['pagesize']];
    }

    /**
     * [银行明细个人信息]
     * @return [array] [description]
     */
    public function actionOwner()
    {
    	$account_id = Yii::$app->request->get('account_id');

    	if(empty($account_id)){
    		return ['code'=>parent::$CODE_ERR,'message'=>'用户id不能为空'];
    	}

    	$account = BankApp::getownerinfo($account_id);

    	if($account == false){
    		return parent::sendMessageJson('此用户不存在');
    	}

    	return parent::sendMessageJson('获取数据成功',200,$account);

    	// $model = BankAccount::find()->where(['account_id'=>$account_id,'disabled'=>0])->asArray()->one();
    }

    /**
     * [明细列表排序]
     * @return [type] [array]
     */
    public function actionActivityList()
    {
    	$account_id = Yii::$app->request->get('user_id');

    	if(empty($account_id)){
    		return parent::sendMessageJson('用户id不能为空');
    	}

    	$page = Yii::$app->request->get('page',1);

    	$get = Yii::$app->request->get();

    	$query = (new \yii\db\Query())->select(['activity_id','type','project_id','name','surplus_value','surplus_gold','all_cost','status','apply_user_id','handler_user_id','create_time','priority'])
    								->from(Activity::tableName().' AS act')
                                    ->orderBy(['last_modify'=>SORT_DESC])
    								->andWhere(['handler_user_id'=>$account_id,'status'=>5,'disabled'=>0]);
        //遍历$get 处理查询条件
    	$query = UrlHandler::handle_get($query,$get,['page','create_time','user_id']);

        $query = BankApp::getQueryByTime($get,$query);

        // var_dump($query->createCommand()->getSql());

    	$data = BankApp::pagination($query,20,$page);

    	//格式化数据
    	if($data['list']){
    		$data = BankApp::Formatdata($data);
    	}

    	return ['code'=>self::$CODE_SUC,'message'=>'获取数据成功','data'=>$data['list'],'page'=>$data['pagesize']];

    }

    /**
     * [创建人、项目list]
     * @return [array] [description]
     */
    public function actionSearchInfo()
    {
       // $apply_user_list = User::find()->where(['disabled'=>0])->asArray()->all();
       $apply_user_list = (new \yii\db\Query())->select(['user_id','name'])
                            ->from(User::tableName().' AS user')
                            ->where(['disabled'=>0])
                            ->all();
        $project_list = (new \yii\db\Query())->select(['project_id','name'])
                            ->from(Project::tableName().' AS pro')
                            ->where(['disabled'=>0])
                            ->all();
        return parent::sendMessageJson('获取数据成功',self::$CODE_SUC,['apply_user_list'=>$apply_user_list,'project_list'=>$project_list]);

    }

    /**
     * [待入账列表]
     * @return [type] [description]
     */
    public function actionRecorded()
    {
        $account_id = Yii::$app->request->get('user_id');

        if(empty($account_id)){
            return parent::sendMessageJson('用户id不能为空');
        }

        $page = Yii::$app->request->get('page',1);

        $get = Yii::$app->request->get();

        $query = (new \yii\db\Query())->select(['activity_id','type','project_id','name','surplus_value','surplus_gold','all_cost','status','apply_user_id','handler_user_id','create_time','priority'])
                                    ->from(Activity::tableName().' AS act')
                                    ->orderBy(['last_modify'=>SORT_DESC])
                                    ->andWhere(['handler_user_id'=>$account_id,'status'=>4,'disabled'=>0]);
        //遍历$get 处理查询条件
        $query = UrlHandler::handle_get($query,$get,['page','create_time','user_id']);

        $query = BankApp::getQueryByTime($get,$query);

        // var_dump($query->createCommand()->getSql());

        $data = BankApp::pagination($query,20,$page);

        //格式化数据
        if($data['list']){
            $data = BankApp::Formatdata($data);
        }

        return ['code'=>self::$CODE_SUC,'message'=>'获取数据成功','data'=>$data['list'],'page'=>$data['pagesize']];
    }


    /**
     * [待审核列表]
     * @return [type] [description]
     */
    public function actionReview()
    {
        $account_id = Yii::$app->request->get('user_id');

        if(empty($account_id)){
            return parent::sendMessageJson('用户id不能为空');
        }

        $page = Yii::$app->request->get('page',1);

        $get = Yii::$app->request->get();

        $query = (new \yii\db\Query())->select(['activity_id','type','project_id','name','surplus_value','surplus_gold','all_cost','status','apply_user_id','handler_user_id','create_time','priority'])
                                    ->from(Activity::tableName().' AS act')
                                    ->orderBy(['last_modify'=>SORT_DESC])
                                    ->andWhere(['apply_user_id'=>$account_id,'status'=>4,'disabled'=>0]);
        //遍历$get 处理查询条件
        $query = UrlHandler::handle_get($query,$get,['page','create_time','user_id']);

        $query = BankApp::getQueryByTime($get,$query);

        // var_dump($query->createCommand()->getSql());

        $data = BankApp::pagination($query,20,$page);

        //格式化数据
        if($data['list']){
            $data = BankApp::Formatdata($data);
        }

        return ['code'=>self::$CODE_SUC,'message'=>'获取数据成功','data'=>$data['list'],'page'=>$data['pagesize']];
    }

    /**
     * [actionNumber 待审核和待入账数量]
     * @return [type] [description]
     */
    public static function number($list)
    {
        foreach ($list as $k => $v) {
            $list[$k]['record_number'] = Activity::find()->where(['handler_user_id'=>$v['user_id'],'status'=>4,'disabled'=>0])->count();
            $list[$k]['review_number'] = Activity::find()->where(['apply_user_id'=>$v['user_id'],'status'=>4,'disabled'=>0])->count();
            $list[$k]['all_value'] = round($v['all_value'],1);
            $list[$k]['all_gold'] = round($v['all_gold'],1);
            $list[$k]['all_cost'] = round($v['all_cost'],1);
        }

        return $list;
    }

}
